package com.projles.ttd;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;

import com.projles.ttd.minigames.MiniGameAzarActivity;
import com.projles.ttd.minigames.MiniGameCalculadoraActivity;
import com.projles.ttd.minigames.MiniGameCartasActivity;
import com.projles.ttd.minigames.MiniGameQuizActivity;
import com.projles.ttd.util.Jogador;
import com.projles.ttd.util.Player;

public class HomeActivity extends Activity implements OnClickListener{

	private Random geradorRandomico = new Random();
	Random rand = new Random();

	//criar uma const para cada minigame criado
	private final int MINIGAME_CALCULADORA = 0;
	private final int MINIGAME_QUIZ = 1;
	private final int MINIGAME_CARTAS = 2;

	private final int CALCULADORA = 0;
	private final int QUIZ = 1;
	private final int CARTAS = 2;
	private final int ALEATORIO = 3;
	
	private int[] listaMinigames = new int[] {
											  MINIGAME_CALCULADORA, 
											  MINIGAME_QUIZ,
											  MINIGAME_CARTAS};
	
	private Button btGerenciaJogadores;
	private Button opcoes;
	private Button btPlacar;
	private Button btSom;
	private ImageView btSite;
	
	private Player player;
	
	private List<Jogador> jogadores;
	
	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
		
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        
        Bundle params = getIntent().getExtras();
        jogadores = (ArrayList<Jogador>) params.get("jogadores");   // recuperando a lista de jogadores passada pela activity cadastro
        
        opcoes = (Button) findViewById(R.id.bt_opcoes);
        opcoes.setOnClickListener(this);
        
        btSite = (ImageView) findViewById(R.id.logo_img);
        btSite.setOnClickListener(this);
        
        Gallery galleriaMinigames = (Gallery) findViewById(R.id.galleria);
		
		galleriaMinigames.setAdapter(new ImageAdapter(this));
		
		galleriaMinigames.setSelection(1);
		galleriaMinigames.setSpacing(1);
		
		galleriaMinigames.setOnItemClickListener(new OnItemClickListener() {
			
			@SuppressWarnings("rawtypes")
			public void onItemClick(AdapterView parent, View v, int position, long id) {
				
				player.click();
				
				switch (position) {
				case CALCULADORA:
					iniciaMiniGameCalculadora();
					break;

				case QUIZ:
					iniciaMiniGameQuiz();
					break;
					
				case CARTAS:
					iniciaMiniGameCartas();
					break;
	
				case ALEATORIO:
					rodaGameAleatoriamente();
					break;
					
				default:
					break;
				}
			}
		});
        
		player = Player.getPlayer(this);
		
        btGerenciaJogadores = (Button) findViewById(R.id.bt_gerenciar_jogadores);
        btGerenciaJogadores.setOnClickListener(this);
        
        btPlacar = (Button) findViewById(R.id.bt_placar);
        btPlacar.setOnClickListener(this);
        
        btSom = (Button) findViewById(R.id.bt_som);
        btSom.setOnClickListener(this);
        
        verificaSom();
        
    }

	@Override
	public void onClick(View v) {
		
		player.click();
		
		switch (v.getId()) {
		
		case R.id.bt_gerenciar_jogadores:
			iniciarGerenciaJogadores();
			break;
			
		case R.id.bt_placar:
			iniciarPlacar();
			break;
			
		case R.id.bt_opcoes:
			iniciaOpcoes();
			break;
			
		case R.id.bt_som:
			player.setMute(!player.isMuted());
			SharedPreferences config = getSharedPreferences(OpcoesActivity.PREFS_NAME, 0);
			OpcoesActivity.salvarOpcoes(player, config);
			verificaSom();
			break;
			
		case R.id.logo_img:
			iniciarSobre();
			break;
	
			
		default:
			break;
		
		}
		
	}

	private void iniciarSobre() {
		Intent i = new Intent(this, SobreActivity.class);
		startActivity(i);
	}

	private void verificaSom() {
		if (player.isMuted()) {
			btSom.setBackgroundResource(R.drawable.semsom);
		}
		else {
			btSom.setBackgroundResource(R.drawable.comsom);
		}
	}
	
	private void rodaGameAleatoriamente() {

		int gameEscolhido = geradorRandomico.nextInt(listaMinigames.length);
		
		switch (gameEscolhido) {

		case MINIGAME_CALCULADORA:
			iniciaMiniGameCalculadora();
			break;
		
		case MINIGAME_QUIZ:
			iniciaMiniGameQuiz();
			break;
			
		case MINIGAME_CARTAS:
			iniciaMiniGameCartas();
			break;
		}
	}

	private void iniciaMiniGameQuiz() {
    	Intent i = new Intent(HomeActivity.this, MiniGameQuizActivity.class);
		i.putExtra("jogadores", (Serializable) jogadores);

		startActivityForResult(i, 0);
	}

	private void iniciaMiniGameCalculadora() {
		Intent i = new Intent(HomeActivity.this, MiniGameCalculadoraActivity.class);
		i.putExtra("jogadores", (Serializable) jogadores);

		startActivityForResult(i, 0);
	}
    
	private void iniciaMiniGameCartas() {
		Intent i = new Intent(HomeActivity.this, MiniGameCartasActivity.class);
		i.putExtra("jogadores", (Serializable) jogadores);
		
		
		startActivityForResult(i, 0);
	}
	
    public void iniciaOpcoes (){
    	Intent i = new Intent(HomeActivity.this, OpcoesActivity.class);
    	startActivityForResult(i, 0);
    }

    private void iniciarGerenciaJogadores() {
    	Intent i = new Intent(this, GerenciaJogadoresActivity.class);
    	i.putExtra("jogadores", (Serializable) jogadores);
    	startActivityForResult(i, 0);
    }
    
    private void iniciarPlacar() {
    	Intent i = new Intent(this, PlacarActivity.class);
    	i.putExtra("jogadores", (Serializable) jogadores);   	
    	startActivity(i);
    }
    
    private void inicializarMiniGameAzar() {
    	Intent i = new Intent(HomeActivity.this, MiniGameAzarActivity.class);
    	i.putExtra("jogadores", (Serializable) jogadores);
    	
    	startActivityForResult(i, 0);
    }
    
    @SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		verificaSom();
		
		if (data != null) {
			Bundle params = data.getExtras();
	    	
	    	jogadores = (ArrayList<Jogador>) params.get("listaAtualizada");
	    	
		}
		
		if (MiniGameAzarActivity.bebeAleatoriamente() && resultCode == RESULT_OK) {
  			inicializarMiniGameAzar();
  		}
	}
    
    public class ImageAdapter extends BaseAdapter {
		private Context myContext;
		
		Integer[] imageIDs = {
				R.drawable.calculadora,
				R.drawable.quiz,
				R.drawable.cartas,
				R.drawable.aleatorio
		};
		
		public ImageAdapter(Context c) { this.myContext = c; }
		
		public int getCount() { return this.imageIDs.length; }
		
		public Object getItem(int position) { return position; }
		
		public long getItemId(int position) { return position; }
		
		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			
			ImageView imageView = new ImageView(myContext);
			imageView.setImageResource(imageIDs[position]);
			
			imageView.setBackgroundResource(android.R.drawable.alert_light_frame);
			
			return imageView;
		}
	}
}